<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫雷游戏</title>
    <style>
        :root {
            --primary-color: #4f46e5;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
            --light-color: #f3f4f6;
            --dark-color: #1f2937;
            --cell-size: 30px;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f9fafb;
            color: var(--dark-color);
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }

        .game-container {
            max-width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-top: 20px;
        }

        .game-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .difficulty-selector {
            display: flex;
            gap: 10px;
        }

        .difficulty-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            background-color: var(--light-color);
            color: var(--dark-color);
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
        }

        .difficulty-btn.active {
            background-color: var(--primary-color);
            color: white;
        }

        .game-info {
            display: flex;
            gap: 20px;
        }

        .info-box {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: var(--light-color);
            padding: 8px 16px;
            border-radius: 6px;
            min-width: 80px;
        }

        .info-label {
            font-size: 12px;
            color: #6b7280;
        }

        .info-value {
            font-size: 20px;
            font-weight: bold;
        }

        .mines-count {
            color: var(--danger-color);
        }

        .timer {
            color: var(--primary-color);
        }

        .restart-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            background-color: var(--primary-color);
            color: white;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .restart-btn:hover {
            background-color: #4338ca;
        }

        .board {
            display: grid;
            grid-template-columns: repeat(var(--cols), var(--cell-size));
            grid-template-rows: repeat(var(--rows), var(--cell-size));
            gap: 2px;
            background-color: #d1d5db;
            border: 2px solid #d1d5db;
            border-radius: 4px;
            margin-bottom: 20px;
            overflow: hidden;
        }

        .cell {
            width: var(--cell-size);
            height: var(--cell-size);
            background-color: #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            cursor: pointer;
            user-select: none;
            transition: all 0.1s;
        }

        .cell:hover {
            background-color: #d1d5db;
        }

        .cell.revealed {
            background-color: #f9fafb;
        }

        .cell.mine {
            background-color: var(--danger-color);
            color: white;
        }

        .cell.flagged {
            background-color: var(--warning-color);
            color: white;
        }

        .cell-1 { color: #3b82f6; }
        .cell-2 { color: #10b981; }
        .cell-3 { color: #ef4444; }
        .cell-4 { color: #7c3aed; }
        .cell-5 { color: #f59e0b; }
        .cell-6 { color: #ec4899; }
        .cell-7 { color: #6366f1; }
        .cell-8 { color: #14b8a6; }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 100;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }

        .modal.active {
            opacity: 1;
            pointer-events: all;
        }

        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 12px;
            text-align: center;
            max-width: 400px;
            width: 90%;
            transform: translateY(20px);
            transition: transform 0.3s;
        }

        .modal.active .modal-content {
            transform: translateY(0);
        }

        .modal-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .modal-message {
            margin-bottom: 20px;
            color: #6b7280;
        }

        .modal-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            background-color: var(--primary-color);
            color: white;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s;
        }

        .modal-btn:hover {
            background-color: #4338ca;
        }

        .win .modal-title {
            color: var(--success-color);
        }

        .lose .modal-title {
            color: var(--danger-color);
        }

        @media (max-width: 768px) {
            :root {
                --cell-size: 25px;
            }
        }

        @media (max-width: 480px) {
            :root {
                --cell-size: 20px;
            }
            
            .game-header {
                flex-direction: column;
                align-items: stretch;
            }
            
            .game-info {
                justify-content: space-between;
                width: 100%;
            }
            
            .info-box {
                min-width: 60px;
                padding: 6px 12px;
            }
            
            .info-value {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <h1>扫雷游戏</h1>
    
    <div class="game-container">
        <div class="game-header">
            <div class="difficulty-selector">
                <button class="difficulty-btn active" data-difficulty="beginner">初级</button>
                <button class="difficulty-btn" data-difficulty="intermediate">中级</button>
                <button class="difficulty-btn" data-difficulty="expert">高级</button>
            </div>
            
            <div class="game-info">
                <div class="info-box">
                    <div class="info-label">剩余地雷</div>
                    <div class="info-value mines-count">10</div>
                </div>
                <div class="info-box">
                    <div class="info-label">时间</div>
                    <div class="info-value timer">0</div>
                </div>
                <button class="restart-btn">
                    <span>重新开始</span>
                </button>
            </div>
        </div>
        
        <div class="board" id="board"></div>
    </div>
    
    <div class="modal" id="resultModal">
        <div class="modal-content">
            <div class="modal-title">游戏结束</div>
            <div class="modal-message" id="modalMessage"></div>
            <button class="modal-btn" id="modalBtn">再来一局</button>
        </div>
    </div>

    <script>
        // 游戏状态
        const gameState = {
            difficulty: 'beginner',
            rows: 9,
            cols: 9,
            mines: 10,
            board: [],
            revealed: 0,
            flagged: 0,
            gameOver: false,
            firstClick: true,
            timer: 0,
            timerInterval: null,
            startTime: null
        };

        // DOM 元素
        const boardElement = document.getElementById('board');
        const minesCountElement = document.querySelector('.mines-count');
        const timerElement = document.querySelector('.timer');
        const difficultyButtons = document.querySelectorAll('.difficulty-btn');
        const restartButton = document.querySelector('.restart-btn');
        const resultModal = document.getElementById('resultModal');
        const modalMessage = document.getElementById('modalMessage');
        const modalBtn = document.getElementById('modalBtn');

        // 初始化游戏
        function initGame() {
            // 清除之前的游戏状态
            clearInterval(gameState.timerInterval);
            gameState.board = [];
            gameState.revealed = 0;
            gameState.flagged = 0;
            gameState.gameOver = false;
            gameState.firstClick = true;
            gameState.timer = 0;
            gameState.startTime = null;
            
            // 更新UI
            timerElement.textContent = '0';
            minesCountElement.textContent = gameState.mines;
            boardElement.innerHTML = '';
            boardElement.style.setProperty('--rows', gameState.rows);
            boardElement.style.setProperty('--cols', gameState.cols);
            
            // 创建棋盘
            for (let i = 0; i < gameState.rows; i++) {
                gameState.board[i] = [];
                for (let j = 0; j < gameState.cols; j++) {
                    gameState.board[i][j] = {
                        isMine: false,
                        isRevealed: false,
                        isFlagged: false,
                        neighborMines: 0
                    };
                    
                    const cell = document.createElement('div');
                    cell.className = 'cell';
                    cell.dataset.row = i;
                    cell.dataset.col = j;
                    
                    cell.addEventListener('click', handleCellClick);
                    cell.addEventListener('contextmenu', handleCellRightClick);
                    
                    boardElement.appendChild(cell);
                }
            }
        }

        // 放置地雷
        function placeMines(firstRow, firstCol) {
            let minesPlaced = 0;
            
            while (minesPlaced < gameState.mines) {
                const row = Math.floor(Math.random() * gameState.rows);
                const col = Math.floor(Math.random() * gameState.cols);
                
                // 确保第一次点击的格子及其周围没有地雷
                if (Math.abs(row - firstRow) <= 1 && Math.abs(col - firstCol) <= 1) {
                    continue;
                }
                
                if (!gameState.board[row][col].isMine) {
                    gameState.board[row][col].isMine = true;
                    minesPlaced++;
                }
            }
            
            // 计算每个格子周围的地雷数量
            for (let i = 0; i < gameState.rows; i++) {
                for (let j = 0; j < gameState.cols; j++) {
                    if (!gameState.board[i][j].isMine) {
                        gameState.board[i][j].neighborMines = countNeighborMines(i, j);
                    }
                }
            }
        }

        // 计算周围地雷数量
        function countNeighborMines(row, col) {
            let count = 0;
            
            for (let i = Math.max(0, row - 1); i <= Math.min(gameState.rows - 1, row + 1); i++) {
                for (let j = Math.max(0, col - 1); j <= Math.min(gameState.cols - 1, col + 1); j++) {
                    if (gameState.board[i][j].isMine) {
                        count++;
                    }
                }
            }
            
            return count;
        }

        // 处理格子点击
        function handleCellClick(e) {
            e.preventDefault();
            
            if (gameState.gameOver) return;
            
            const row = parseInt(e.target.dataset.row);
            const col = parseInt(e.target.dataset.col);
            const cell = gameState.board[row][col];
            
            if (cell.isRevealed || cell.isFlagged) return;
            
            // 第一次点击
            if (gameState.firstClick) {
                gameState.firstClick = false;
                placeMines(row, col);
                startTimer();
            }
            
            // 点到地雷
            if (cell.isMine) {
                revealAllMines();
                gameOver(false);
                return;
            }
            
            // 翻开格子
            revealCell(row, col);
            
            // 检查是否胜利
            if (gameState.revealed === gameState.rows * gameState.cols - gameState.mines) {
                gameOver(true);
            }
        }

        // 处理右键点击（标记地雷）
        function handleCellRightClick(e) {
            e.preventDefault();
            
            if (gameState.gameOver || gameState.firstClick) return;
            
            const row = parseInt(e.target.dataset.row);
            const col = parseInt(e.target.dataset.col);
            const cell = gameState.board[row][col];
            
            if (cell.isRevealed) return;
            
            // 切换标记状态
            cell.isFlagged = !cell.isFlagged;
            
            if (cell.isFlagged) {
                e.target.classList.add('flagged');
                gameState.flagged++;
            } else {
                e.target.classList.remove('flagged');
                gameState.flagged--;
            }
            
            // 更新剩余地雷数
            minesCountElement.textContent = gameState.mines - gameState.flagged;
        }

        // 翻开格子
        function revealCell(row, col) {
            if (row < 0 || row >= gameState.rows || col < 0 || col >= gameState.cols) return;
            
            const cell = gameState.board[row][col];
            const cellElement = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
            
            if (cell.isRevealed || cell.isFlagged || cell.isMine) return;
            
            cell.isRevealed = true;
            gameState.revealed++;
            cellElement.classList.add('revealed');
            
            // 显示周围地雷数
            if (cell.neighborMines > 0) {
                cellElement.textContent = cell.neighborMines;
                cellElement.classList.add(`cell-${cell.neighborMines}`);
            } else {
                // 如果是空白格子，递归翻开周围的格子
                for (let i = Math.max(0, row - 1); i <= Math.min(gameState.rows - 1, row + 1); i++) {
                    for (let j = Math.max(0, col - 1); j <= Math.min(gameState.cols - 1, col + 1); j++) {
                        if (i !== row || j !== col) {
                            revealCell(i, j);
                        }
                    }
                }
            }
        }

        // 显示所有地雷
        function revealAllMines() {
            for (let i = 0; i < gameState.rows; i++) {
                for (let j = 0; j < gameState.cols; j++) {
                    const cell = gameState.board[i][j];
                    const cellElement = document.querySelector(`.cell[data-row="${i}"][data-col="${j}"]`);
                    
                    if (cell.isMine) {
                        cellElement.classList.add('mine');
                        cellElement.textContent = '💣';
                    }
                }
            }
        }

        // 开始计时器
        function startTimer() {
            gameState.startTime = Date.now();
            gameState.timerInterval = setInterval(() => {
                gameState.timer = Math.floor((Date.now() - gameState.startTime) / 1000);
                timerElement.textContent = gameState.timer;
            }, 1000);
        }

        // 游戏结束
        function gameOver(isWin) {
            gameState.gameOver = true;
            clearInterval(gameState.timerInterval);
            
            // 显示结果模态框
            resultModal.classList.add('active');
            if (isWin) {
                resultModal.querySelector('.modal-content').classList.add('win');
                resultModal.querySelector('.modal-content').classList.remove('lose');
                document.querySelector('.modal-title').textContent = '恭喜你赢了！';
                modalMessage.textContent = `用时: ${gameState.timer}秒`;
            } else {
                resultModal.querySelector('.modal-content').classList.add('lose');
                resultModal.querySelector('.modal-content').classList.remove('win');
                document.querySelector('.modal-title').textContent = '很遗憾你输了！';
                modalMessage.textContent = '下次再接再厉！';
            }
        }

        // 设置难度
        function setDifficulty(difficulty) {
            gameState.difficulty = difficulty;
            
            switch (difficulty) {
                case 'beginner':
                    gameState.rows = 9;
                    gameState.cols = 9;
                    gameState.mines = 10;
                    break;
                case 'intermediate':
                    gameState.rows = 16;
                    gameState.cols = 16;
                    gameState.mines = 40;
                    break;
                case 'expert':
                    gameState.rows = 16;
                    gameState.cols = 30;
                    gameState.mines = 99;
                    break;
            }
            
            // 更新UI
            difficultyButtons.forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.difficulty === difficulty) {
                    btn.classList.add('active');
                }
            });
            
            initGame();
        }

        // 事件监听
        difficultyButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                setDifficulty(btn.dataset.difficulty);
            });
        });

        restartButton.addEventListener('click', initGame);
        modalBtn.addEventListener('click', () => {
            resultModal.classList.remove('active');
            initGame();
        });

        // 初始化游戏
        setDifficulty('beginner');
    </script>
</body>
</html>